﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ReportFlat.Common;
using ReportFlat.DataAccess;
using System.Collections;


namespace ReportFlat.Web.server.customer
{
    /// <summary>
    /// Supplier 的摘要说明
    /// </summary>
    public class Customer : BaseHandler
    {
        /// <summary>
        /// 保存
        /// </summary>
        [UseDB(Transaction = true)]
        public void Save()
        {
            c_customer obj = ToPo<c_customer>("FContactsInfo,FProjectInfo,FTraceInfo");
            //名称不能重复
            int count = dao.GetRowCount("from c_customer where FName=" + obj.FName.wrap() + " and FID<>" + obj.FID);
            if (count > 0)
            {
                jsonResult = JSONHelper.ToErroJson("客户名称重复，系统已经存在！");
                return;
            }
            //省份和城市
            t_areas areas = dao.Get<t_areas>(obj.FProviceID);
            obj.FProvice = areas == null ? "" : areas.FName;
            areas = dao.Get<t_areas>(obj.FCityID);
            obj.FCity = areas == null ? "" : areas.FName;
            if (obj.FID == 0)
            {
                obj.FCreateDate = DateTime.Now;
                dao.Save(obj);
            }
            else
            {
                dao.Update(obj);
            }
            jsonResult = JSONHelper.SuccessJson;
        }

        /// <summary>
        /// 删除
        /// </summary>
        [UseDB(Transaction = true)]
        public void Delete()
        {
            int custID = Convert.ToInt32(Request["FID"]);
            int count = dao.GetRowCount("from c_contacts where FCustID=" + custID);
            if (count>0)
            {
                //jsonResult = JSONHelper.ToErroJson("有合同关联引用，不能删除！");
                //return;
            }
            dao.Delete(new c_customer() { FID = custID });
            //TODO:删除关联的，要不一堆垃圾数据
            dao.ExcuteByHSql("delete from c_contacts where FCustID=" + custID);
            dao.ExcuteByHSql("delete from c_project where FCustID=" + custID);
            dao.ExcuteByHSql("delete from c_project_trace where FCustID=" + custID);
            dao.ExcuteByHSql("delete from c_project_bankroll where FCustID=" + custID);
            jsonResult = JSONHelper.SuccessJson;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        [UseDB]
        public void GetList()
        {
            int start = int.Parse(Request["start"]);
            int limit = int.Parse(Request["limit"]);
            string sWhere = Request["where"];
            string findAll = JSONHelper.GetString(Request["oWhere"], "FINDALL");
            //加权限控制
            if(!GMLogin.isAdminUser()){
                sWhere = sWhere.and("FUserID=" + GMLogin.UserID);
            }
            //全文搜索
            if (!string.IsNullOrEmpty(findAll))
            {
                sWhere = sWhere.and(findAll.likeAll<c_customer>());
            }
            int rowCount;
            IList<c_customer> list = dao.GetList<c_customer>(out rowCount, sWhere, "FProvice,FCity", start, limit);
            jsonResult = JSONHelper.ToSucJson((IList)list, rowCount);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        [UseDB]
        public void GetOne()
        {
            c_customer obj = dao.Get<c_customer>(Convert.ToInt32(Request["FID"]));
            jsonResult = JSONHelper.ToSucJson("data", obj);
        }

        /// <summary>
        /// 获取下拉列表
        /// </summary>
        [UseDB]
        public void GetOptions()
        {
            string where = "1=2";
            if (!string.IsNullOrEmpty(Request["FID"]))
            {
                if (Tools.isNumberic(Request["FID"]))
                {
                    where += "or FID=" + Request["FID"];
                }
            }
            if (!string.IsNullOrEmpty(Request["FName"]))
            {
                 where += "or FName like " + Request["FName"].Replace("'","").like();
            }
            IList<c_customer> list = dao.GetList<c_customer>(where, "", 0, 20);
            jsonResult = JSONHelper.ToSucJson("options", JSONHelper.CustomList((IList)list, "FID,FName"));
        }

        /// <summary>
        /// 下载Excel
        /// </summary>
        [UseDB]
        public void ExportExcel()
        {
            string sWhere = this.context.Server.UrlDecode(Request.Params["where"].ToString());
            //加权限控制
            if (!GMLogin.isAdminUser())
            {
                sWhere = sWhere.and("FUserID=" + GMLogin.UserID);
            }
            int rowCount;
            IList<c_customer> list = dao.GetList<c_customer>(out rowCount, sWhere, "FProvice,FCity", 0, 10000);
            CreateExcel(list);
        }

        private void CreateExcel(IList<c_customer> list)
        {
            String fileName = "客户" + DateTime.Now.ToString("yyyyMMdd") + ".csv";
            String[] Columns = { "客户名称", "意向客户类别","客户类别","法人", "所属行业", "省份", "城市",
                                 "地址", "是否万家企业", "是否高耗能企业","所属业务员","备注", "联系人信息", "项目信息","跟进信息"};
            HttpResponse resp;
            resp = this.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            string colHeaders = "", ls_item = "";

            int i = 0;
            int cl = Columns.Length;

            //取得数据表各列标题，各标题之间以t分割，最后一个列标题后加回车符 
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))//最后一列，加n
                {
                    colHeaders += Columns[i] + "\r\n";
                }
                else
                {
                    colHeaders += Columns[i] + ",";
                }

            }
            resp.Write(colHeaders);
            //向HTTP输出流中写入取得的数据信息 
            //String[] Columns = { "客户名称", "客户类别", "所属行业", "省份", "城市",
            //                     "地址", "是否万家企业", "是否高耗能企业", "法人", "联系人信息", "项目信息","备注","所属业务员"};
            //逐行处理数据   
            foreach (c_customer row in list)
            {
                ls_item += FormatHtmlStr(row.FName) + ",";
                ls_item += FormatHtmlStr(row.FGradeYX) + ",";
                ls_item += FormatHtmlStr(row.FGrade) + ",";
                ls_item += FormatHtmlStr(row.FCorporation) + ",";
                ls_item += FormatHtmlStr(row.FIndustry) + ",";
                ls_item += FormatHtmlStr(row.FProvice) + ",";
                ls_item += FormatHtmlStr(row.FCity) + ",";
                ls_item += FormatHtmlStr(row.FAddress) + ",";
                ls_item += FormatHtmlStr(row.F10000) + ",";
                ls_item += FormatHtmlStr(row.FHeightEnergy) + ",";
                ls_item += FormatHtmlStr(row.UserName) + ",";
                ls_item += FormatHtmlStr(row.FNote) + ",";
                ls_item += FormatHtmlStr(row.FContactsInfo) + ",";
                ls_item += FormatHtmlStr(row.FProjectInfo) + ",";
                ls_item += FormatHtmlStr(row.FTraceInfo) + "\r\n";
                resp.Write(ls_item);
                ls_item = "";
            }
            //resp.End();
        }

        private string FormatHtmlStr(string s)
        {
            if (s == null)
            {
                return "";
            }
            s = s.Replace("<font color=blue>", "");
            s = s.Replace("</font>", "");
            s = s.Replace("</font>", "");
            s = s.Replace(",", ";");
            s = s.Replace("，", ";");
            s = s.Replace("<br>", "     ");
            s = s.Replace("\r\n", "     ");
            s = s.Replace("\n", "     ");
            return s.ToString();
        }
    }
}